package org.chench.extra;

import org.zeromq.SocketType;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 使用见简单的请求-应答模式
 * 请求必须是客户端发起,服务端响应
 * @author chench9@lenovo.com
 * @desc org.chench.extra.HelloWorldClient
 * @date 3/20/19 11:08 AM
 */
public class HelloWorldClient {
    public static void main(String[] args) {
        try {
            startClientByJeromq();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 使用ZeroMQ的纯Java实现版本jeromq
    private static void startClientByJeromq() throws IOException {
        try(ZContext context = new ZContext()) {
            System.out.println("Connecting to hello world server");
            // 创建主动发送请求的Socket
            ZMQ.Socket socket = context.createSocket(SocketType.REQ);
            socket.connect("tcp://localhost:5555");

            // 连接服务器
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while((line = reader.readLine()) != null) {
                // 先发送请求
                socket.send(line.getBytes(ZMQ.CHARSET),0);

                // 再接收数据
                byte[] resp = socket.recv(0);
                System.out.println("Received: [" + new String(resp, ZMQ.CHARSET) + "]");
            }
        }
    }

    // 用过jzmq使用libzmq
    private static void startClientByJzmq() throws IOException {
        try(ZContext context = new ZContext()) {
            System.out.println("Connecting to hello world server");
            // 创建主动发送请求的Socket
            ZMQ.Socket socket = context.createSocket(ZMQ.REQ);
            socket.connect("tcp://localhost:5555");

            // 连接服务器
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while((line = reader.readLine()) != null) {
                // 先发送请求
                socket.send(line.getBytes(),0);

                // 再接收数据
                byte[] resp = socket.recv(0);
                System.out.println("Received: [" + new String(resp) + "]");
            }
        }
    }
}
